﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HuChaHuRen.HeNan.XiangCheng.Common;
using HuChaHuRen.HeNan.XiangCheng.Common.Events;
using HuChaHuRen.HeNan.XiangCheng.Models.Messages;
using HuChaHuRen.HeNan.XiangCheng.Upload;
using Microsoft.Win32;
using Quartz;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Threading;

namespace HuChaHuRen.HeNan.XiangCheng
{
    public class MainWindowVM:ObservableObject,IListener<string>,IListener<JobActivityMessage>,IListener<OnAppCloseMessage>
    {
        private string _studyStatus;
        public string StudyUploadStatus 
        { 
            get => _studyStatus; 
            set => SetProperty(ref _studyStatus, value);
        }

        private string _imgStatus;
        public string ImgUploadStatus
        {
            get => _imgStatus;
            set => SetProperty(ref _imgStatus, value);
        }

        private bool _isAutoStart;

        public bool IsAutoStart
        {
            get => _isAutoStart;
            set => SetProperty(ref _isAutoStart, value);
        }

        public ObservableCollection<string> LogList { get; set; }

        private string rawStudyStatus { get; set; }
        private string rawImgStatus { get; set; }

        System.Timers.Timer studyTmr = new System.Timers.Timer();
        System.Timers.Timer ImgTmr = new System.Timers.Timer();

        private int studyRunningTimeCount = 0;
        private int imgRunningTimeCount = 0;

        private ScheduleManager _scheManager;

        private object SyncLock = new object();

        private string key
        {
            get
            {
                return "HuChaHuRen.HeNan.XiangCheng";
            }
        }


        public MainWindowVM()
        {
            LogList = new ObservableCollection<string>();
            //跨线程操作
            BindingOperations.EnableCollectionSynchronization(LogList, SyncLock);

            MessageHub.DefaultMessageHub.AddListener(this);
           _scheManager = new ScheduleManager();
           _scheManager.Start();

            RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            object existedItem = registryKey.GetValue(key);
            if (existedItem == null)
            {
                IsAutoStart = false;
            }
            else
            {
                IsAutoStart = true;

            }
        }

        private RelayCommand _pauseCmd;
        public RelayCommand PauseCmd
        {
            get
            {
                if(_pauseCmd == null)
                {
                    _pauseCmd = new RelayCommand(() =>
                    {
                        if (_scheManager != null)
                        {
                            _scheManager.Pause();
                        }
                    });
                }
                return _pauseCmd;
            }
        }

        private RelayCommand _resumeCmd;

        public RelayCommand ResumeCmd
        {
            get
            {
                return _resumeCmd ?? (_resumeCmd = new RelayCommand(() =>
                {
                    if (_scheManager != null)
                    {
                        _scheManager.Resume();
                    }
                }));
            }
        }

        private RelayCommand _exitCmd;

        public RelayCommand ExitCmd
        {
            get
            {
                return _exitCmd ?? (_exitCmd = new RelayCommand(() =>
                {
                    if (_scheManager != null)
                    {
                        _scheManager.Stop();
                    }

                    if(studyTmr != null)
                    {
                        studyTmr.Stop();
                        studyTmr.Dispose();
                    }

                    if(ImgTmr != null)
                    {
                        ImgTmr.Stop();
                        ImgTmr.Dispose();
                    }

                    Environment.Exit(0);
                }));
            }
        }

        private RelayCommand _execStuUploadCmd;

        public RelayCommand ExecStudyUploadNowCmd
        {
            get
            {
                return _execStuUploadCmd ?? (_execStuUploadCmd = new RelayCommand(() =>
                {
                    var diagResult = MessageBox.Show("是否执行 StudyUploadJob ?", "确认", MessageBoxButton.OKCancel);
                    if (diagResult == MessageBoxResult.OK)
                    {
                        LogList.Add("手动执行 StudyUploadJob");
                        Task.Run(() =>
                        {
                            IJob jobs = new PACSUploadJob();
                            jobs.Execute(null);
                        });

                    }

                }));
            }
        }

        private RelayCommand _execImgUploadCmd;

        public RelayCommand ExecImageUploadNowCmd
        {
            get
            {
                return _execImgUploadCmd ?? (_execImgUploadCmd = new RelayCommand(() =>
                {
                var diagResult = MessageBox.Show("是否执行 DicomTransferJob ?", "确认", MessageBoxButton.OKCancel);
                    if (diagResult == MessageBoxResult.OK)
                    {
                        LogList.Add("手动执行 DicomTransferJob");
                        Task.Run(() =>
                        {
                            IJob jobs = new DicomTransferJob();
                            jobs.Execute(null);
                        });
                    }
                }));
            }
        }


        private RelayCommand _editBaseCfgCmd;

        public RelayCommand EditBaseConfigCmd
        {
            get
            {
                return _editBaseCfgCmd ?? (_editBaseCfgCmd = new RelayCommand(() =>
                {
                    ConfigHelp.OpenConfigDir();
                }));
            }
        }



        private RelayCommand<string> _copyCmd;

        public RelayCommand<string> CopyCmd
        {
            get
            {
                return _copyCmd ?? (_copyCmd = new RelayCommand<string>((p) =>
                {
                    if (!string.IsNullOrEmpty(p))
                    {
                        Clipboard.SetText(p); 
                    }
                }));
            }
        }

        private RelayCommand _clearLogCmd;

        public RelayCommand ClearLogCmd
        {
            get
            {
                return _clearLogCmd ?? (_clearLogCmd = new RelayCommand(() =>
                {
                    if(LogList != null && LogList.Any())
                    {
                        LogList.Clear();
                    }
                }));
            }
        }

        private RelayCommand _autoStartCmd;

        public RelayCommand AutoStartCmd
        {
            get
            {
                return _autoStartCmd ?? (_autoStartCmd = new RelayCommand(() =>
                {
                    RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    object existedItem = registryKey.GetValue(key);
                    if (existedItem == null)
                    {
                        registryKey.SetValue(key, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
                        MessageBox.Show("已设置开机自启");
                    }
                    else
                    {
                        registryKey.DeleteValue(key);
                        MessageBox.Show("已取消开机自启");
                    }
                    
                }));
            }
        }

        public void Handle(string message)
        {
            Debug.WriteLine($"Received message: {message}");

            if (LogList != null)
            {
                lock(SyncLock)
                {
                    if(LogList.Count > 1000)
                    {
                        LogList.Clear();
                    }

                    LogList.Add(message);
                }
            }
        }

        public void Handle(JobActivityMessage message)
        {
            Debug.WriteLine($"Received message: Job:{message.JobType}, Status:{message.Status}");

            if(message.Status.Contains("运行中"))
            {
                if(message.JobType == 0)
                {
                    rawStudyStatus = message.Status;
                    StudyUploadStatus = rawStudyStatus.ToString();
                    
                    studyTmr.Interval = 1000;
                    studyTmr.AutoReset = true;
                    studyTmr.Elapsed += (s,e) =>
                    {
                        studyRunningTimeCount += 1;
                        StudyUploadStatus = $"{rawStudyStatus}({studyRunningTimeCount}秒)";
                    };
                    studyTmr.Enabled = true;
                    studyTmr.Start();
                }
                else if(message.JobType == 1)
                {
                    rawImgStatus = message.Status;
                    ImgUploadStatus = rawImgStatus.ToString();

                    ImgTmr.Interval = 1000;
                    ImgTmr.AutoReset = true;
                    ImgTmr.Elapsed += (s, e) =>
                    {
                        imgRunningTimeCount += 1;
                        ImgUploadStatus = $"{rawImgStatus}({imgRunningTimeCount}秒)";
                    };
                    ImgTmr.Enabled = true;
                    ImgTmr.Start();
                }
            }
            else if(message.Status.Contains("就绪"))
            {
                if (message.JobType == 0)
                {
                    rawStudyStatus = message.Status;
                    StudyUploadStatus = rawStudyStatus.ToString();

                    if(studyTmr != null && studyTmr.Enabled)
                    {
                        studyRunningTimeCount = 0;
                        studyTmr.Stop();
                        studyTmr.Dispose();
                    }
                }
                else if (message.JobType == 1)
                {
                    rawImgStatus = message.Status;
                    ImgUploadStatus = rawImgStatus.ToString();

                    if (ImgTmr != null && ImgTmr.Enabled)
                    {
                        imgRunningTimeCount = 0;
                        ImgTmr.Stop();
                        ImgTmr.Dispose();
                    }
                }
            }
        }

        public void Handle(OnAppCloseMessage message)
        {
            this.ExitCmd.Execute(null);
        }
    }
}
